# coding=utf-8
# encoding=utf-8

import DataBase.Connect as db
import DataBase.Model as m_models
import socket
from logHelper import logger


def initDB():
    m_models.Base.metadata.create_all(bind=db.engine)


def insert(element):
    """
    单条插入mysql数据库
    """
    flag = False
    try:
        db.session.add(element)
        db.session.commit()
        flag = True
    except Exception as e:
        logger.error(msg=e)
        db.session.rollback()
        db.session.flush()
    finally:

        return flag


def insertBatch(element_list):
    """
    批量插入数据库
    """
    successNum = 0
    failNum = 0
    for element in element_list:
        if insert(element):
            successNum += 1
        else:
            failNum += 1
    return successNum, failNum


def GetAcStatusByDeviceAdd(element):
    try:
        returnedData = db.session.query(m_models.ACStatus).filter_by(DeviceAddress=element).first()
        return returnedData
    except Exception as e:
        logger.error(msg=e,
                     extra={'clientip': socket.gethostbyname(socket.gethostname()),
                            'msgtype': 'EntityDataConductError'})


def GetAcInfoByDeviceId(element):
    """
    返回根据deviceId查询到的第一个数据
    :param element,查询数据的deviceId:
    :return 查询到的模型list:
    """
    try:
        returnedData = db.session.query(m_models.ACInfo).filter_by(DeviceID=element.DeviceID).first()
        return returnedData
    except Exception as e:
        logger.error(msg=e,
                     extra={'clientip': socket.gethostbyname(socket.gethostname()),
                            'msgtype': 'EntityDataConductError'})


def GetAcInfoAll():
    try:
        returnedData = db.session.query(m_models.ACInfo).all()
        return returnedData
    except Exception as e:
        logger.error(msg=e,
                     extra={'clientip': socket.gethostbyname(socket.gethostname()),
                            'msgtype': 'EntityDataConductError'})


def GetWaterFirst(element):
    """
    返回根据deviceaddress查询到的第一个数据
    :param element,查询数据的deviceaddress: 
    :return 查询到的模型list: 
    """
    try:
        returnedData = db.session.query(m_models.ACStatusWater).filter_by(DeviceAddress=element.DeviceAddress).first()
        return returnedData
    except Exception as e:
        logger.error(msg=e,
                     extra={'clientip': socket.gethostbyname(socket.gethostname()),
                            'msgtype': 'EntityDataConductError'})


def GetAcSendingList():
    """
    根据流水表里数据生成‘发送类’
    :return:待发送数据模型list  
    """
    try:
        returnedData = db.session.query(m_models.ACStatusWater, m_models.ACInfo) \
            .filter(m_models.ACStatusWater.DeviceAddress == m_models.ACInfo.DeviceAddress).all()
        acSendlist = []
        for row in returnedData:
            acSendlist.append(m_models.ACSend(row[0], row[1]).__dict__)
        return acSendlist
    except Exception as e:
        logger.error(msg=e,
                     extra={'clientip': socket.gethostbyname(socket.gethostname()),
                            'msgtype': 'EntityDataConductError'})


def GetStatusWater():
    """
    返回本地数据库ACStatusWater表里所有的数据
    :return ACStatusWater表里所有的数据: 
    """
    try:
        returnedData = db.session.query(m_models.ACStatusWater).all()
        return returnedData
    except Exception as e:
        logger.error(msg=e,
                     extra={'clientip': socket.gethostbyname(socket.gethostname()),
                            'msgtype': 'EntityDataConductError'})


def GetCrlSended():
    """
    返回ACControl表里下发执行过的数据,并将这些数据装换成ACCrlSend数据
    :return ACControl表里下发执行过并完成转换的数据:
    """
    try:
        returnedData = db.session.query(m_models.ACControl).filter(m_models.ACControl.status != u'未发送').all()
        acCrlSendlist = []
        for row in returnedData:
            acCrlSendlist.append(m_models.ACCrlSend(row).__dict__)
        return acCrlSendlist
    except Exception as e:
        logger.error(msg=e,
                     extra={'clientip': socket.gethostbyname(socket.gethostname()),
                            'msgtype': 'EntityDataConductError'})


def GetCrlSending():
    """
    返回ACControl表里下发执行过的数据,并将这些数据装换成ACCrlSend数据
    :return ACControl表里下发执行过并完成转换的数据:
    """
    try:
        returnedData = db.session.query(m_models.ACControl).filter(m_models.ACControl.status == u'未发送').all()
        return returnedData
    except Exception as e:
        logger.error(msg=e,
                     extra={'clientip': socket.gethostbyname(socket.gethostname()),
                            'msgtype': 'EntityDataConductError'})


def deleteWaterData(element):
    '''
    删除流水表中的信息
    :param element,将要删除的流水表的模型: 
    :return: 
    '''
    try:
        returnedData = db.session.query(m_models.ACStatusWater).filter_by(id=element['id']).delete()
        db.session.commit()
        return returnedData
    except Exception as e:
        db.session.rollback()
        db.session.flush()
        logger.error(msg=e,
                     extra={'clientip': socket.gethostbyname(socket.gethostname()),
                            'msgtype': 'EntityDataConductError'})


def deleteSendedCrlData(element):
    """
    删除控制表中已发送的数据
    :return 查询到的将要删除的数据: 
    """
    try:
        returnedData = db.session.query(m_models.ACControl).filter_by(id=element['id']).delete()
        db.session.commit()
        return returnedData
    except Exception as e:
        logger.error(msg=e,
                     extra={'clientip': socket.gethostbyname(socket.gethostname()),
                            'msgtype': 'EntityDataConductError'})


def updateAcCtrl(ctrl_cmd):
    try:
        db.session.query(m_models.ACControl).filter_by(DeviceID=ctrl_cmd.DeviceID). \
            update({m_models.ACControl.status: ctrl_cmd.status})
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        db.session.flush()
        logger.error(msg=e,
                     extra={'clientip': socket.gethostbyname(socket.gethostname()),
                            'msgtype': 'EntityDataConductError'})


def updateAcStatus(status):
    try:
        db.session.query(m_models.ACStatus).filter_by(DeviceAddress=status.DeviceAddress). \
            update({
                m_models.ACStatus.ATemp: status.ATemp,
                m_models.ACStatus.Aoc: status.Aoc,
                m_models.ACStatus.Dwind: status.Dwind,
                m_models.ACStatus.FModel: status.FModel,
                m_models.ACStatus.HElec: status.HElec,
                m_models.ACStatus.ErrorMessage: status.ErrorMessage,
                m_models.ACStatus.Updatetime: status.Updatetime,
                m_models.ACStatus.Aoctime: status.Aoctime,
                m_models.ACStatus.eTemp: status.eTemp

        })
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        db.session.flush()
        logger.error(msg=e,
                     extra={'clientip': socket.gethostbyname(socket.gethostname()),
                            'msgtype': 'EntityDataConductError'})
